<template>
  <div>
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <span class="text-large font-600 mr-3">试卷预览</span>
      </template>
      <template #extra>
        <el-button 
          :type="speechService.isSpeaking.value ? 'danger' : 'primary'" 
          :icon="speechService.isSpeaking.value ? Mute : Reading"
          @click="handleSpeech"
          text 
          bg
        >
          {{ speechService.isSpeaking.value ? '停止朗读' : '朗读试卷' }}
        </el-button>
      </template>
    </el-page-header>
    
    <el-card v-loading="loading">
      <div v-if="exam" class="exam-preview-container">
        <h2 class="exam-title">{{ exam.title }}</h2>
        <div class="exam-meta">
          <span>创建时间: {{ formatDate(exam.createdAt) }}</span>
          <span>状态: <el-tag :type="getStatusType(exam.status)" size="small">{{ getStatusText(exam.status) }}</el-tag></span>
          <span v-if="exam.durationInMinutes">时长: {{ exam.durationInMinutes }} 分钟</span>
        </div>

        <el-divider />

        <div v-for="(q, index) in exam.questions" :key="index" class="question-block">
          <p class="question-title">
            <strong>{{ index + 1 }}. ({{ q.type === 'multiple-choice' ? '选择题' : '判断题' }})</strong>
            <span v-if="q.topic" class="topic-tag">[{{ q.topic }}]</span>
            {{ q.question }}
          </p>
          <ul v-if="q.options" class="options-list">
            <li v-for="(option, key) in q.options" :key="key"><strong>{{ key }}.</strong> {{ option }}</li>
          </ul>
          <p class="correct-answer">
            <el-tag type="warning" effect="plain" size="small">正确答案: {{ q.answer }}</el-tag>
          </p>
        </div>
      </div>
      <el-empty v-if="!loading && !exam" description="无法加载试卷详情" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import examService from '../../services/examService';
import speechService from '../../services/speechService';
import { Reading, Mute } from '@element-plus/icons-vue';

const props = defineProps({
  id: {
    type: [String, Number],
    required: true,
  },
});

const loading = ref(true);
const exam = ref(null);
const router = useRouter();

// 计算属性，用于拼接所有问题和答案，形成一个完整的朗读文本
const fullExamText = computed(() => {
  if (!exam.value) return '';
  
  let text = `试卷标题: ${exam.value.title}. `;
  exam.value.questions.forEach((q, index) => {
    const type = q.type === 'multiple-choice' ? '选择题' : '判断题';
    text += `第 ${index + 1} 题, ${type}. 知识点: ${q.topic || '常规'}. 题目: ${q.question}. `;
    if (q.options) {
      text += '选项: ';
      for (const [key, value] of Object.entries(q.options)) {
        text += `${key}, ${value}. `;
      }
    }
    text += `正确答案是: ${q.answer}. `;
  });
  return text;
});

// 调用 speechService 的方法
const handleSpeech = () => {
  speechService.toggleSpeech(fullExamText.value);
};

const fetchExamDetails = async () => {
  try {
    loading.value = true;
    exam.value = await examService.getExamById(props.id);
  } catch (error) {
    ElMessage.error(error.message || '获取试卷详情失败');
  } finally {
    loading.value = false;
  }
};

const goBack = () => {
  router.push({ name: 'TeacherExamList' });
};

const getStatusType = (status) => {
  if (status === 'PUBLISHED') return 'success';
  if (status === 'FINISHED') return 'info';
  return 'warning';
};

const getStatusText = (status) => {
  if (status === 'PUBLISHED') return '已发布';
  if (status === 'FINISHED') return '已结束';
  return '草稿';
};

// 从 ExamList.vue 复制过来的 formatDate 方法
const formatDate = (dateArray) => {
  // 1. 首先检查输入是否是一个有效的数组
  if (!Array.isArray(dateArray) || dateArray.length < 3) {
    // 如果数据格式不正确，返回一个提示信息
    return '日期格式错误';
  }

  // 2. 从数组中提取年月日等信息
  //    关键：将数组中的月份（dateArray[1]）减 1，以匹配 JavaScript 的 0-indexed 月份
  const year = dateArray[0];
  const month = dateArray[1] - 1; // 月份从 0 开始，所以需要减 1
  const day = dateArray[2];
  const hours = dateArray[3] || 0;
  const minutes = dateArray[4] || 0;
  const seconds = dateArray[5] || 0;

  // 3. 使用这些数字参数创建 Date 对象
  const date = new Date(year, month, day, hours, minutes, seconds);

  // 4. 检查日期是否有效，防止出现类似 [2025, 13, 1] 这样的错误数据
  if (isNaN(date.getTime())) {
    return '无效日期';
  }

  // 5. 进行格式化并返回
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit', // 显示小时
    minute: '2-digit', // 显示分钟
    second: '2-digit' // 显示秒
  });
};


onMounted(fetchExamDetails);

// 在组件卸载时确保停止朗读
onBeforeUnmount(() => {
  speechService.stop();
});
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}
.exam-preview-container {
  padding: 20px;
}
.exam-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 10px;
}
.exam-meta {
  text-align: center;
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}
.exam-meta span {
  margin: 0 15px;
}
.question-block {
  margin-bottom: 25px;
  line-height: 1.7;
}
.question-title {
  font-size: 16px;
  margin-bottom: 10px;
}
.topic-tag {
  color: #409EFF;
  margin: 0 5px;
}
.options-list {
  list-style-type: none;
  padding-left: 20px;
  margin: 10px 0;
}
.options-list li {
  margin-bottom: 8px;
}
.correct-answer {
  margin-top: 10px;
}
</style>